import React, { useEffect, useRef, useState } from 'react'
import { LoginFormValues } from '../../types/data.d'
import { NavBar, Form, Input, Button, Toast } from 'antd-mobile'
import styles from './index.module.scss'
import { useHistory } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { getCode, login } from '@/store/actions/login'
import { AxiosError } from 'axios'
import { setToken } from '@/utils/storage'
import { InputRef } from 'antd-mobile/es/components/input'
const Login = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // const { token } = useSelector((state) => state.login)
  const onFinish = async (values: LoginFormValues) => {
    await dispatch(login(values))
    Toast.show({
      content: '登录成功',
      afterClose: () => {
        console.log('after')
        history.push('/home')
      },
    })
  }
  const [form] = Form.useForm()
  const inputRef = useRef<InputRef>(null)
  const [timeDown, setTimeDown] = useState(0)
  const timeRef = useRef(0)
  const onGetCode = async () => {
    const mobile = form.getFieldValue('mobile')
    const mobileError = form.getFieldError('mobile')
    if (!mobile || mobileError.length) {
      inputRef.current?.focus()
      return
    }
    // console.log('手机号合法')
    await dispatch(getCode(mobile))
    setTimeDown(5)
    timeRef.current = window.setInterval(() => {
      console.log('定时器')

      setTimeDown((time) => time - 1)
    }, 1000)
    // setInterval(() => {}, 1000)
  }

  useEffect(() => {
    if (timeDown === 0) {
      clearInterval(timeRef.current)
    }
  }, [timeDown])

  useEffect(() => {
    return window.clearInterval(timeRef.current)
  }, [])

  return (
    <div className={styles.login}>
      {/* 导航区域 */}
      <NavBar onBack={() => history.goBack()} />
      {/* 表单区域 */}
      <div className="login-form">
        <h2 className="title">短信登录</h2>
        <Form onFinish={onFinish} form={form}>
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              },
            ]}
          >
            <Input ref={inputRef} placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[{ required: true, message: '手机号不能为空' }]}
            extra={
              <span onClick={timeDown === 0 ? onGetCode : undefined}>
                {timeDown === 0 ? '发送验证码' : `${timeDown}S后重新获取`}
              </span>
            }
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item>
            <Button type="submit" block color="primary" size="large">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
